package com.scu.phototab.push.connector;

import com.scu.phototab.push.handler.Http2pushLogicHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import protobuf.codec.PacketDecoder;
import protobuf.codec.PacketEncoder;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tianfei on 2017/4/20.
 */
@Component
public class HttpServer2pushLogic {

    Logger logger= LoggerFactory.getLogger(HttpServer2pushLogic.class);

    private static HttpServer2pushLogic instance;

//    @Value("${logic.ip}")
//    private static String logicIP;
//    @Value("${logic.port}")
//    private static int logicPort;

    private static String logicIP ="127.0.0.1";
    private static int logicPort = 7070;

    private HttpServer2pushLogic(){

        logger.info("System initialing.. Http will start to connect to logic in 1 second");
        //连接到Logic
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                logger.info("Http start connecting to logic.....");
                connect();
            }
        },1000);
    }

    public synchronized HttpServer2pushLogic getInstance(){
        if (instance == null){
            instance=new HttpServer2pushLogic();
        }
        return instance;
    }


    public void connect(){
        EventLoopGroup group = null;
        try {

        group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast("MessageDecoder", new PacketDecoder());
                        p.addLast("MessageEncoder", new PacketEncoder());
                        p.addLast(new Http2pushLogicHandler());
                    }
                });
        b.connect(logicIP,logicPort);

        }catch (Exception e){
            group.shutdownGracefully();
        }
    }


}
